# -*- coding: utf-8 -*-
from django.db import models
from web_app.parser import process_search_url
from django.contrib.auth.models import User
from custom_exceptions import EmptyResultsTable


class UserProfile(models.Model):
    user = models.OneToOneField(User)
    calendar_id = models.CharField(max_length=60)


class UserUrl(models.Model):
    user = models.ForeignKey(User)
    url = models.CharField(max_length=400)

    def save(self, *args, **kwargs):
        self.remove_old_user_url_adverts()
        super(UserUrl, self).save(*args, **kwargs)
        try:
            process_search_url(self, UserUrlAdvert, True)
        except EmptyResultsTable, e:
            print e

    def remove_old_user_url_adverts(self):
        old_user_url_adverts = UserUrlAdvert.objects.filter(user_url=self)
        for adv in old_user_url_adverts:
            adv.delete()

class UserUrlAdvert(models.Model):
    user_url = models.ForeignKey(UserUrl)
    advert_id = models.IntegerField()
    advert_price = models.IntegerField()
    processed = models.BooleanField(default=False)
